/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.more;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jivesoftware.smack.XMPPException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.service.JaberClientService;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.MD5;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 主页面
 * 显示全部问题
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class RegisterActivity extends Activity
{
    private EditText txtAccount;
    
    private EditText txtPassword;
    
    private RadioGroup radioGender;
    
    private RadioButton btnBoy;
    
    private RadioButton btnGirl;
    
    private RadioButton btnUn;
    
    private Button btnEnter;
    
    private String strAccount;
    
    private String strPassword;
    
    private String strGender="1";
    private DolphinApplication app;
    private JaberClientService jaberClientService;
    String msg;//网络提示信息
    private StringBuffer url = new StringBuffer(DolphinApplication.URL);
    private ProgressDialog progressDialog = null;
    boolean success;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        getElement();
        setElementEvent();
        app = (DolphinApplication)getApplication();
        jaberClientService = JaberClientService.getInstance();
    }
    
    private void getElement()
    {
        btnEnter = (Button)findViewById(R.id.btn_enter);
        txtAccount = (EditText)findViewById(R.id.txt_account);
        txtPassword = (EditText)findViewById(R.id.txt_password);
        radioGender = (RadioGroup)findViewById(R.id.radio_gender);
        btnBoy = (RadioButton)findViewById(R.id.radio_boy);
        btnGirl = (RadioButton)findViewById(R.id.radio_girl);
        btnUn = (RadioButton)findViewById(R.id.radio_un);
    }
    
    private void setElementEvent()
    {
        txtAccount.requestFocus();
        btnEnter.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                strAccount = txtAccount.getText().toString();
                strPassword = txtPassword.getText().toString();
                if (StringUtil.isEmpty(strAccount)
                        || StringUtil.isEmpty(strPassword))
                {
                    Toast.makeText(RegisterActivity.this,
                            "请输入账号或密码",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                //strPassword = ;
                //提交注册信息
                UserInfo user = new UserInfo();
                if(!StringUtil.isEmpty(app.getUserId()))
                {
                    user.setUserId(Integer.valueOf(app.getUserId()));
                }
                user.setAccount(strAccount);
                user.setPassword(MD5.code(strPassword));
                user.setGender(strGender);
                user.setMac(app.getMac());
                //打开进度条窗口
                progressDialog = ProgressDialog.show(RegisterActivity.this, "请稍等...", "提交注册中...", true);
                //执行提交任务
                new RegisterTask().execute(user);
            }
        });
        radioGender.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                
                if (checkedId == btnBoy.getId())
                {
                    strGender = UserInfo.GENDER_BOY;
                }
                else if (checkedId == btnGirl.getId())
                {
                    strGender = UserInfo.GENDER_GIRL;
                }
                else if (checkedId == btnUn.getId())
                {
                    strGender = UserInfo.GENDER_UN;
                }
                
            }
        });
    }
    
    class RegisterTask extends AsyncTask<UserInfo, Void, String>
    {
        @Override
        protected String doInBackground(UserInfo... params)
        {
            if(!RequestUtils.getInstall().isConnect(RegisterActivity.this))
            {
                return "网络不可用";
            }
            String userId = submit(params[0]);
            if(!StringUtil.isEmpty(userId))
            {
                LogUtil.d("将用户ID及账号密码写入到本地");
                //将用户ID及账号密码写入到本地
                app.setUserId(userId);
                app.setAccount(strAccount, strPassword);
                success=true;
            }
            return msg;
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(result != null)
            {
                LogUtil.d(result);
                Toast.makeText(RegisterActivity.this, result, Toast.LENGTH_LONG).show();
            }
            //关闭进度条窗口
            progressDialog.dismiss();
            if(success)
            {
                //如果注册成功，将注册窗口关闭
                RegisterActivity.this.finish();
            }
            
        }
    }
    //提交注册
    private String submit(UserInfo user)
    {
        
        String userId=null;
        
        try
        {
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("userId",user.getUserId()==null?null:String.valueOf(user.getUserId())));
            param.add(new BasicNameValuePair("account",user.getAccount()));
            param.add(new BasicNameValuePair("password",user.getPassword()));
            param.add(new BasicNameValuePair("gender",user.getGender()));
            param.add(new BasicNameValuePair("mac",user.getMac()));
            String json = RequestUtils.getInstall().getHttpJson(url.append("user/regUser.php").toString(), param);
            LogUtil.d(json);
            JSONObject data = new JSONObject(json);
            String msgCode = data.getString("msgCode");
            String desc = data.getString("desc");
            if("1".equals(msgCode))
            {
                userId = desc;
                msg="注册成功";
                try {
                    jaberClientService.connect();
                    //jaberClientService.register(user.getAccount(), user.getPassword());
                    jaberClientService.login(user.getAccount(), strPassword);
                } catch (XMPPException e) {
                    LogUtil.e("连接openfire服务器失败", e);
                }
            }else
            {
                msg=desc;
                LogUtil.d(desc);
            }
        }
        catch (JSONException e)
        {
            LogUtil.e("" ,e);
        }
        
        return userId;
    }
}
